package com.tgh.au.c5;

import java.util.concurrent.TimeUnit;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.view.KeyEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.SurfaceHolder.Callback;

public class GameSurface extends SurfaceView implements Callback, Runnable {
	int count=0;
	int y=50;
	boolean loop=false;
	SurfaceHolder holder;
	public GameSurface(Context context) {
		super(context);
		holder=getHolder();
		holder.addCallback(this);
		setFocusable(true);
		loop=true;
	}

	@Override
	public void run() {
		while (loop) {
			try {
				TimeUnit.MILLISECONDS.sleep(100);
			} catch (Exception e) {
				
			}
			synchronized (holder) {
				draw();
			}
		}
	}

	private void draw() {
		if (holder==null) {
			return;
		}
		Canvas canvas = holder.lockCanvas();
		if (canvas==null) {
			return;
		}
		if (count<100) {
			count++;
		}else {
			count=0;
		}
		Paint paint=new Paint();
		paint.setAntiAlias(true);
		paint.setColor(Color.BLACK);
		//先绘制矩形，起到清屏的作用
		canvas.drawRect(0,0,320,480, paint);
		switch (count%4) {
		case 0:
			paint.setColor(Color.BLUE);
			break;
		case 1:
			paint.setColor(Color.GREEN);
			break;
		case 2:
			paint.setColor(Color.RED);
			break;
		case 3:
			paint.setColor(Color.YELLOW);
			break;
		}
		canvas.drawCircle((320-25)/2, y, 50, paint);
		holder.unlockCanvasAndPost(canvas);
	}

	@Override
	public void surfaceCreated(SurfaceHolder holder) {
		new Thread(this).start();
	}

	@Override
	public void surfaceChanged(SurfaceHolder holder, int format, int width,
			int height) {}

	@Override
	public void surfaceDestroyed(SurfaceHolder holder) {
		loop=false;
	}
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		switch (keyCode) {
		case KeyEvent.KEYCODE_DPAD_DOWN:
			y+=3;
			break;
		case KeyEvent.KEYCODE_DPAD_UP:
			y-=3;
			break;
		}
		return true;
	}
}
